// 判断
const form = layui.form;
form.verify({
    articleTitle: [
        /^[\u4E00-\u9FA5a-zA-Z0-9_-]+$/,
        "标题只能是中英文, 数字下划线中划线组成"
    ],
    // 分类判断
    cate: function(){
        return $("select[name=cate_id]").val().length == 0 && "请选择文章类别"
    }
}) 


initEditor()

//渲染列表
function render() {
    axios({
        method:'GET',
        url:"http://api-breakingnews-web.itheima.net/my/article/cates",
        headers:{
            Authorization:localStorage.getItem('token')
        }
    }).then(({data:res})=>{
    //     console.log(res)
        //判断请求成功
        if(res.status===0){

        res.data.forEach(obj=>{
    const theOpt = `<option value="${obj.Id}" lay-verify="cate">${obj.name}</option>`
    $("select[name=cate_id]").append(theOpt)
        })
        //等循环结束之后.在执行
        form.render('select','edit')

        }
         
    })
  }
  render()

  let imgUrl = ''
  $(".select").on('click',function () {
       $("#file").click()
  })
  $("#file").on('change',function (e) {
       const files = e.target.files
       if(files.length === 0) return
       const blobUrl = window.URL.createObjectURL(files[0])
       $("#image").prop('src',blobUrl)
       imgUrl = files[0]
  })

  $('form').on('submit',function (e) {
      e.preventDefault()
    const htmlStr = tinyMCE.activeEditor.getContent();
    let fd = new FormData($('form')[0])
    fd.set('content',htmlStr)
    fd.append('cover_img',imgUrl)
    fd.forEach((value,key)=>{
        console.log('value --- key',value,key)
    })
    // console.log(fd)
    axios({
        method:'POST',
        url:"http://api-breakingnews-web.itheima.net/my/article/add",
        headers:{
            Authorization:localStorage.getItem('token')
        },data:fd
    }).then(({data:res})=>{
    //     console.log(res)
        layer.msg(res.message)
        //判断请求成功
        if(res.status===0){
            window.parent.$('#wzlist a').click()
            location.href = './../list/list.html'
        }
    })
  })

